# 自动部署处理类
import json
from typing import Dict, Any

import requests

# 部署服务器地址
DEPLOYMENT_API_URL = "http://127.0.0.1:8990/auto/deploy/bot"

supported_city_map = {
    "云平台": "YunPingTai",
    "锐通测试": "RuiTongTest",
    "广安": "GuangAn",
    "武胜": "WuSheng",
    "德阳": "DeYang",
    "荆州": "JingZhou",
    "雅安": "YaAn",
    "遂宁": "SuiNing",
    "黄陂": "HuangPi",
    "锐视机电": "RuiShiJiDian",
    "平凉": "PingLiang",
}


# invoke 方法
def invoke(message: str, tool: Dict[str, Any], result_params: Dict[str, Any]) -> str:
    """
    自动部署工具调用方法
    
    Args:
        message: 用户消息
        tool: 工具信息字典
        result_params: 包含提取信息的参数字典
    
    Returns:
        str: 调用结果信息
    """
    print(f"成功调用工具: {tool['name']}")
    print("message", message)

    # 从 json 对象 result_params 中提取 extracted_info 即请求的参数
    params = {}
    if 'extracted_info' in result_params:
        params = result_params['extracted_info']

    # 检查必要参数
    required_params = tool.get('parameters', [])
    missing_params = [param for param in required_params if param not in params]

    if missing_params:
        return f"参数缺失: {', '.join(missing_params)}, 无法执行自动部署"

    # 确定 city 是否在 supported_city_map 中，存在替换成 value
    if 'city' in params:
        city = params['city']
        if city in supported_city_map:
            params['city'] = supported_city_map[city]
    else:
        return "参数缺失: city, 无法执行自动部署"
    # projectList 是字符串，不是列表，将其转化成列表
    if 'projectList' in params:
        project_list = params['projectList']
        if isinstance(project_list, str):
            params['projectList'] = [project.strip() for project in project_list.split(",")]
    print("params:", params)
    try:
        # 调用post请求
        response = requests.post(
            DEPLOYMENT_API_URL,
            json=params,
            headers={"Content-Type": "application/json"},
            timeout=30
        )

        # 检查响应
        if response.status_code == 200:
            # 返回调用信息
            required_str = str(tool.get('required'))
            return f"调用工具 {tool['name']}; 参数：{json.dumps(params, ensure_ascii=False)}, {required_str}"
        else:
            return f"调用失败: {response.status_code}, {response.text}"

    except Exception as e:
        return json.dumps({
            "status": "error",
            "message": f"部署过程发生错误: {str(e)}",
            "details": None
        }, ensure_ascii=False)

    finally:
        # 处理完成后，清理资源或执行其他操作
        pass
